//
//  YYPhotoCollectionViewController.swift
//  CodeLibrary_Swift
//
//  Created by 陆文宇 on 2017/2/8.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit
import Photos

protocol YYPhotoCollectionViewControllerDelegate {
    
    func photoCollectionViewController(_ controller: YYPhotoCollectionViewController, choosedPhotos photos: Array<YYPhotoModel>) -> Void
    
}

private let reuseIdentifier = "Cell"

class YYPhotoCollectionViewController: UICollectionViewController, UINavigationControllerDelegate {
    
    let assetCollection: PHAssetCollection
    var chooseClosure: ((YYPhotoModel) -> Void)!
    lazy var dataSource: Array<YYPhotoModel> = []
    lazy var choosedPhotos: Array<YYPhotoModel> = []
    init(collectionViewLayout layout: UICollectionViewLayout, assetCollection: PHAssetCollection) {
        self.assetCollection = assetCollection
        
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.isNavigationBarHidden = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor.white
        navigationController?.delegate = self
        
        DispatchQueue.global().async {
            self.dataSource.append(contentsOf: YYPhotoHandler.photos(in: self.assetCollection, isOriginal: true))
            DispatchQueue.main.async {
                self.collectionView?.reloadData()
                self.collectionView?.scrollToItem(at: IndexPath(item: self.dataSource.count - 1, section: 0), at: .bottom, animated: false)
            }
        }
        
        chooseClosure = {[unowned self] (model) in
            if model.chooseNumber == 0 {
                self.choosedPhotos.append(model)
            } else {
                self.choosedPhotos.remove(at: self.choosedPhotos.index(where: { (m) -> Bool in
                    return m === model
                })!)
                for photo in self.choosedPhotos {
                    if photo.chooseNumber > model.chooseNumber {
                        photo.chooseNumber -= 1
                        self.collectionView?.reloadItems(at: [IndexPath(item: self.dataSource.index(where: { (m) -> Bool in
                            return m === photo
                        })!, section: 0)])
                    }
                }
            }
            
            if self.choosedPhotos.count > 0 {
                self.navigationItem.rightBarButtonItem?.title = "完成"
            } else {
                self.navigationItem.rightBarButtonItem?.title = "取消"
            }
        }
        
        let doneItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(done(sender:)))
        navigationItem.rightBarButtonItem = doneItem

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView?.register(UINib(nibName: "YYPhotoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }
    
    @objc func done(sender: UIBarButtonItem?) -> Void {
        if choosedPhotos.count > 0 {
            YYPhotoCollectionViewCell.choosedCount = 0
            if let delegate = YYImagePickerViewController.delegate {
                if YYPhotoHandler.isRecord {
                    YYPhotoHandler.choosedPhotos?.append(contentsOf: choosedPhotos.map({ (m) -> String in
                        return m.asset.localIdentifier
                    }))
                    NSKeyedArchiver.archiveRootObject(YYPhotoHandler.choosedPhotos!, toFile: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!.appending("/choosedPhotoRecord"))
                }
                delegate.photoCollectionViewController(self, choosedPhotos: choosedPhotos)
            } else {
                print("没有指定代理对象")
                navigationController?.dismiss(animated: true, completion: nil)
            }
        } else {
            navigationController?.dismiss(animated: true, completion: nil)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController is YYAlbumTableViewController {
            YYPhotoCollectionViewCell.choosedCount = 0
        }
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return dataSource.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: YYPhotoCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! YYPhotoCollectionViewCell
    
        // Configure the cell
        let photo: YYPhotoModel = dataSource[indexPath.item]
        cell.model = photo
        cell.controller = self
        
        if YYPhotoHandler.choosedPhotos != nil && YYPhotoHandler.choosedPhotos!.contains(photo.asset.localIdentifier) {
            cell.chooseLabel.isHidden = true
        } else {
            cell.chooseLabel.isHidden = false
        }
    
        return cell
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let imageViewController: YYImageViewController = YYImageViewController(photos: dataSource, currentIndex: indexPath.item)
        imageViewController.chooseClosure = { (index) in
            let indexP = IndexPath(item: index, section: 0)
            let cell: YYPhotoCollectionViewCell = collectionView.cellForItem(at: indexP) as! YYPhotoCollectionViewCell
            cell.tapAction(sender: nil)
        }
        imageViewController.endClosure = { [unowned self] in
            self.done(sender: nil)
        }
        navigationController?.pushViewController(imageViewController, animated: true)
    }

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return false
    }

    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return false
    }

    override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
    
    }
    */

}
